<template>
  <div class="app-container">
    <br>
    <el-tabs v-model="editableTabsValue" type="border-card" @tab-remove="removeTab" >
      <el-tab-pane
        label="卡列表"
        name="卡列表"
      >
        <br>
        <el-button type="primary" @click="addCard">添加卡</el-button>
        <br>
        <br>
        <el-table
          style="width: 100%;white-space: pre-wrap;"
          :data="cardList"
          element-loading-text="Loading"
          border
          fit
          :header-cell-style="{ height: '5px', padding: '0 0' }"
          :cell-style="{padding: '8px 0', height: '50px'}"
        > 
          <el-table-column label="序号" align="center" width="50">
            <template slot-scope="subDrugScope">
              <div>{{ subDrugScope.$index+1 }}</div>
              <el-button class="del-btn"  type="danger" icon="el-icon-delete" circle @click="delDrug(subDrugScope.$index, cardList)"></el-button> 
            </template>
          </el-table-column>
          <el-table-column :label="'卡券商品名称'" align="center" width="140">
            <template slot-scope="subDrugScope">
              <span>{{ subDrugScope.row.name }}</span><br>
            </template>
          </el-table-column>
          <el-table-column :label="'预存/售价'" align="center" width="75" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column :label="'赠送'" align="center" width="75" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.giveaway ? subDrugScope.row.giveaway : '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="'期限天数'" align="center" width="75" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.limitDays }}
            </template>
          </el-table-column>
          <!-- <el-table-column :label="'备注'" align="center" width="140" >
            <template slot-scope="subDrugScope">
              <div class="first-row">
                <el-popover
                  v-model="subDrugScope.row.visible"
                  v-if = "subDrugScope.row.type == 2"
                  placement="right"
                  width="180"
                  trigger="click"
                  >
                  <div class="drugs-item" >
                    <div >开始日期</div>
                    <el-date-picker 
                      style="width: 150px;"
                      size="mini"
                      v-model="subDrugScope.row.startDate"
                      >
                    </el-date-picker>
                  </div>
                  <br>
                  <br>
                  <el-button type="primary" size="small" @click="changeStartDate(subDrugScope.row)" >确定</el-button>
                  <el-button @click="subDrugScope.row.visible = false" size="small" >取消</el-button>
                  
                  <el-button slot="reference" size="mini">选择开始日期</el-button>
                </el-popover>
              </div>
              <span class="second-row" style="left: 3px;" v-if="subDrugScope.row.type == 2" >{{ subDrugScope.row.startDateStr }}</span>

            </template>
          </el-table-column> -->
          <el-table-column :label="'使用说明'" align="center" width="200" >
            <template slot-scope="subDrugScope">
              {{ subDrugScope.row.description }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="操作" align="center" width="300" >
            <template slot-scope="scope">
              <el-button type="success"  @click="updateCard(scope.row)" size="small">修改</el-button>
              <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button>
            </template>
          </el-table-column>
          
        </el-table>
        <el-pagination
          background
          layout="->, total, prev, pager, next"
          :total="this.cardListTotal"
          :current-page="cardListCurrentPage"
          :page-size="pageSize"
          @current-change="clickCardListCurPage"
          >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane
        v-if="isVisibleEditCard"
        label="添加/修改卡"
        name="添加/修改卡"
        :closable="true"
      >
        <el-form ref="cardForm" :model="cardForm" label-width="120px" :rules="cardFormRules" >
          <el-form-item label="类型" prop="type">
            <el-select v-model="cardForm.type" placeholder="请选择">
              <el-option
                v-for="item in cardTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="卡名称" prop="amount">
              <el-input style="width: 200px;" v-model="cardForm.name">
              </el-input>
          </el-form-item>
          <el-form-item :label="cardForm.type !== 2 ? '预存' : '售价'" prop="amount">
              <el-input type="Number" min=0 style="width: 200px;" v-model="cardForm.amount" >
                <template slot="append">
                  元
                </template>
              </el-input>
          </el-form-item>
          <el-form-item v-if="cardForm.type === 3" label="赠送" prop="giveaway">
              <el-input min=0 style="width: 200px;" v-model="cardForm.giveaway" >
                <template slot="append">
                  元
                </template>
              </el-input>
          </el-form-item>
          <el-form-item v-if="cardForm.type == 2" label="期限天数" prop="limitDays">
            <el-input type="Number" min=1 style="width: 200px;" v-model="cardForm.limitDays" >
              <template slot="append">
                天
              </template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item v-if="cardForm.type !== 3" label="折扣" prop="discount">
              <el-input type="Number" min=0 style="width: 200px;" v-model="cardForm.discount" >
                <template slot="append">
                  折
                </template>
              </el-input>
          </el-form-item> -->
          <el-form-item label="商品" prop="drug">
            <div style="text-align: left">
              <el-transfer
                style="text-align: left;display: inline-block"
                v-model="cardForm.drugList"
                filterable
                :filter-method="filterMethod"
                :titles="['所有商品', '折扣商品']"
                :button-texts="['删除', '添加']"
                :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
                @change="handleChange"
                :data="allDrugList">
                <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>
                <!-- <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>
                <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button> -->
              </el-transfer>
            </div>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmCard">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-tab-pane>

    </el-tabs>

  </div>
</template>

<script>

import { getList as getCardList, edit as editCard, add as addCard, del as delCard} from '@/api/card'
import { getList as getActivityList, edit as editActivity, add as addActivity, del as delActivity} from '@/api/activity'
import { getList as getDrugList } from '@/api/drug'

export default {
  name: "Voucher",
  filters: {

  },
  data() {
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateAmount = (rule, value, callback) => {
      if (this.cardForm.type == 1 && !value) callback(new Error('请输入预存金额'))
      else callback()
    }
    const validateDiscount = (rule, value, callback) => {
      if (!value) callback(new Error('请输入折扣'))
      else callback()
    }
    const validateLimitDays = (rule, value, callback) => {
      if (this.cardForm.type == 2 && !value || this.activityForm && !value) callback(new Error('请选择期限天数'))
      else callback()
    }
    const validateStartTime = (rule, value, callback) => {
      if (this.cardForm.type == 2 && !value || this.activityForm && !value) callback(new Error('请选择开始日期'))
      else callback()
    }
    const validateEndTime = (rule, value, callback) => {
      if (this.cardForm.type == 2 && !value || this.activityForm && !value) callback(new Error('请选择结束日期'))
      else callback()
    }
    const validateGiveaway = (rule, value, callback) => {
      if (this.cardForm.type === 3 && !value) callback(new Error('请输入赠送金额'))
      else callback()
    }
    const validateDrugCode1 = (rule, value, callback) => {
      if (this.activityForm.type == 2 && !value) callback(new Error('请选择购买药品'))
      else callback()
    }
    const validateDrugCode1Num = (rule, value, callback) => {
      if (this.activityForm.type == 2 && !value) callback(new Error('请输入药品数量'))
      else callback()
    }
    const validateDrugCode2 = (rule, value, callback) => {
      if (this.activityForm.type == 2 && !value) callback(new Error('清选择优惠药品'))
      else callback()
    }
    const validateDrugCode2Num = (rule, value, callback) => {
      if (this.activityForm.type == 2 && !value) callback(new Error('请输入优惠药品数量'))
      else callback()
    }
    const validateUnitPrice2 = (rule, value, callback) => {
      if (this.activityForm.type == 2 && !value) callback(new Error('请输入优惠药品单价'))
      else callback()
    }
    const validateDrugCode3 = (rule, value, callback) => {
      if (this.activityForm.type == 3 && !value) callback(new Error('清选择优惠药品'))
      else callback()
    }
    const validateBuyNumber = (rule, value, callback) => {
      if (this.activityForm.type == 3 && !value) callback(new Error('请输入药品数量'))
      else callback()
    }
    const validateTotalAmount = (rule, value, callback) => {
      if (this.activityForm.type == 3 && !value) callback(new Error('请输入药品总价'))
      else callback()
    }
    return {
      list: null,
      cardListLoading: true,
      cardListCurrentPage: 1,
      cardListTotal: 0,
      cardListCurIndex: -1,
      cardForm: {},
      pageSize: 10,
      activityForm: {},
      voucherForm: {},
      cardFormRules: {
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        amount: [{ required: true, trigger: 'blur', validator: validateAmount }],
        discount: [{ required: true, trigger: 'blur', validator: validateDiscount }],
        limitDays: [{ required: true, trigger: 'blur', validator: validateLimitDays }],
        giveaway: [{ required: true, trigger: 'blur', validator: validateGiveaway }],
      },
      cardTypeEnum: [{id: 2, name: '期限卡'},  {id: 3, name: '储值卡'}],
      activityFormRules: {
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        amount: [{ required: true, trigger: 'blur', validator: validateAmount }],
        discount: [{ required: true, trigger: 'blur', validator: validateDiscount }],
        startTime: [{ required: true, trigger: 'blur', validator: validateStartTime }],
        endTime: [{ required: true, trigger: 'blur', validator: validateEndTime }],
        drugCode1: [{ required: true, trigger: 'blur', validator: validateDrugCode1 }],
        drugCode1Num: [{ required: true, trigger: 'blur', validator: validateDrugCode1Num }],
        drugCode2: [{ required: true, trigger: 'blur', validator: validateDrugCode2 }],
        drugCode2Num: [{ required: true, trigger: 'blur', validator: validateDrugCode2Num }],
        unitPrice2: [{ required: true, trigger: 'blur', validator: validateUnitPrice2 }],
        drugCode3: [{ required: true, trigger: 'blur', validator: validateDrugCode3 }],
        buyNumber: [{ required: true, trigger: 'blur', validator: validateBuyNumber }],
        totalAmount: [{ required: true, trigger: 'blur', validator: validateTotalAmount }],
      },
      voucherFormRules: {
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        amount: [{ required: true, trigger: 'blur', validator: validateAmount }],
        discount: [{ required: true, trigger: 'blur', validator: validateDiscount }],
        startTime: [{ required: true, trigger: 'blur', validator: validateStartTime }],
        endTime: [{ required: true, trigger: 'blur', validator: validateEndTime }],
      },
      activityTypeEnum: [{id: 1, name: '折扣活动'}, {id: 2, name: '买A优惠B'}, {id: 3, name: '多买优惠'}],
      voucherTypeEnum: [{id: 1, name: '买送券'}, {id: 2, name: '介绍券'}],
      allDrugList: [],
      optionDrugList: [],
      allDrugDisableList: [],
      query: {optionType: 1},
      optionTypeEnum: [{id: 1,name: '卡'}, {id: 2,name: '活动'}, {id: 3,name: '券'}],
      editableTabsValue: '卡列表',
      editableTabs: [],
      isVisibleEditCard: false,
      cardList: [],
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.getCardList(this.currentPage, this.pageSize)
      // all drugs
      getDrugList({currentPage: 1, pageSize: 1000}).then(res=> {
        console.log(res.data)
        res.data.records.forEach(item=> {
          item.key = item.code
          item.label = item.commonName + '/' + item.name + ' ' + item.specs
        })
        this.allDrugList = res.data.records
        this.optionDrugList = JSON.parse(JSON.stringify(res.data.records))
        this.allDrugDisableList = JSON.parse(JSON.stringify(res.data.records))
        this.allDrugDisableList.forEach(item=> {
          item.disabled = true
        })
      })
    },
    getCardList(currentPage, pageSize) {
      this.cardListLoading = true
      getCardList({currentPage: currentPage, pageSize: pageSize}).then(res=>{
        console.log(res)
        this.cardList = res.data
        this.cardListTotal = res.data.length
        this.cardList.forEach(item=> {
          const rule = JSON.parse(item.rule)
          console.log(rule);
          item.amount = Number(rule.amount)
          item.discount = Number(rule.discount)
          item.giveaway = Number(rule.giveaway)
          item.drugList = item.drugCode.split(',')
          if(item.type === 2) {
            item.startTime = rule.startTime
            item.endTime = rule.endTime
          }
        })
        this.cardListLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.cardListLoading = false
      })
    },
    getActivityList(currentPage, pageSize) {
      this.listLoading = true
      getActivityList({currentPage: currentPage, pageSize: pageSize}).then(res=>{
        console.log(res)
        this.list = res.data
        this.total = res.data.length
        this.list.forEach(item=> {
          var rule = JSON.parse(item.rule)
          if(item.type == 1) {
            item.discount = Number(rule.discount)
            console.log()
            item.drugList = rule.drugList
          } else if(item.type == 2) {
            item.drugCode1 = rule.drugCode1
            item.drugCode1Num = rule.drugCode1Num
            item.sourceUnitPrice1 = rule.sourceUnitPrice1
            item.drugCode2 = rule.drugCode2
            item.drugCode2Num = rule.drugCode2Num
            item.sourceUnitPrice2 = rule.sourceUnitPrice2
            item.unitPrice2 = rule.unitPrice2
          } else if(item.type == 3) {
            item.drugCode3 = rule.drugCode3
            item.buyNumber = rule.buyNumber
            item.sourceUnitPrice3 = rule.sourceUnitPrice3
            item.totalAmount = rule.totalAmount
          }
        })
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    clickCardListCurPage(val){
      this.cardListCurrentPage = val
      this.fetchData()
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCard(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addCard() {
      this.reset()
      this.isVisibleEditCard = true
      this.editableTabsValue = '添加/修改卡'
    },
    updateCard(row) {
      this.isVisibleEditCard = true
      this.editableTabsValue = '添加/修改卡'
      this.cardForm = row
    },
    addActivity() {
      this.reset()
      this.dialogTitle = '添加活动'
      this.$set(this.activityForm, 'type', 1)
      this.activityFormVisible = true
    },
    confirmCard() {
      this.$refs.cardForm.validate(valid => {
        if (valid) {
          this.cardForm.rule = JSON.stringify(this.cardForm)
          this.cardForm.drugCode = this.cardForm.drugList.join(',')
          if(this.cardForm.id) {  // update
            console.log(this.cardForm)
            editCard(this.cardForm).then(res=>{
              console.log(res)
              this.$message({
                message: '修改卡成功',
                type: 'success'
              })
              this.cardFormVisible = false
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/voucher', name: "Voucher"})
            }).catch(err=>{
              console.log(err)
            })
          } else { // add
            console.log(this.cardForm)
            addCard(this.cardForm).then(res=>{
              this.cardFormVisible = false
              this.$message({
                message: '添加卡成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/voucher', name: "Voucher"})
            }).catch(err=>{
              console.log(err)
            })
          }
        }
      })
    },
    confirmActivity() {
      this.$refs.activityForm.validate(valid => {
        if (valid) {
          this.activityForm.name = this.activityTypeEnum.filter(item => item.id == this.activityForm.type)[0].name
          this.activityForm.rule = JSON.stringify(this.activityForm)
          this.activityForm.desc = this.activityForm.name
          // this.activityForm.drugCode = this.activityForm.drugList.join(',')
          if(this.activityForm.id) {  // update
            console.log(this.activityForm)
            editActivity(this.activityForm).then(res=>{
              console.log(res)
              this.$message({
                message: '修改活动成功',
                type: 'success'
              })
              this.activityFormVisible = false
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/voucher', name: "Voucher"})
            }).catch(err=>{
              console.log(err)
            })
          } else { // add
            console.log(this.activityForm)
            addActivity(this.activityForm).then(res=>{
              this.activityFormVisible = false
              this.$message({
                message: '添加活动成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/voucher', name: "Voucher"})
            }).catch(err=>{
              console.log(err)
            })
          }
        }
      })
    },
    cancel() {
      this.cardFormVisible = false
      this.cardInfoVisible = false
      this.activityFormVisible = false
      this.activityInfoVisible = false
    },
    reset(){
      this.cardForm = {}
    },
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
    },
    filterMethod(query, item) {
      return item.pinyinCode.indexOf(query) > -1;
    },
    selectFilterMethod(query) {
      if(!query) {
        this.optionDrugList = this.allDrugList
        return
      }
      this.optionDrugList = this.allDrugList.filter(drug=> drug.pinyinCode.indexOf(query) > -1)
    },
    updateDrugCode1(drug, form) {
      this.$set(form, 'sourceUnitPrice1', drug.unitPrice)
      this.optionDrugList = this.allDrugList
    },
    updateDrugCode2(drug, form) {
      this.$set(form, 'sourceUnitPrice2', drug.unitPrice)
      this.optionDrugList = this.allDrugList
    },
    updateDrugCode3(drug, form) {
      this.$set(form, 'sourceUnitPrice3', drug.unitPrice)
      this.optionDrugList = this.allDrugList
    },
    validateNumber(value) {
      const regex = /^(\d+)?(\.\d{1,2})?(\d+\.)?$/;
      // 如果输入值不符合规定的格式，则将inputValue重置为上一次的值
      if (!regex.test(value) || value.split('.').length > 2) {
        this.activityForm.unitPrice2 = value.substring(0, value.length - 1);
      }
    },
    addVoucher() {
      this.reset()
      this.dialogTitle = '添加券'
      this.$set(this.voucherForm, 'type', 1)
      this.voucherFormVisible = true
    },
    removeTab(targetName) {
      if(targetName == '添加/修改卡') {
        this.isVisibleEditCard = false
        this.editableTabsValue = '卡列表'
        this.reset()
      } else if(targetName == '添加/修改券') {
        this.isVisibleEditCard = false
        this.editableTabsValue = '券列表'
        this.reset()
      } else if(targetName == '添加/修改活动') {
        this.isVisibleEditCard = false
        this.editableTabsValue = '活动列表'
        this.reset()
      }
    },
    delDrug(index, list) {
      console.log('DEL drug LIST', list)
      const card = list[index]
      console.log('del card', card)
      this.$confirm('删除 '+ card.name + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        list.splice(index, 1)
        delCard({id: card.id})
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
  }
}
</script>
<style>
.el-transfer-panel{
  width: 350px; /* 左右两个穿梭框的高度和宽度 */
  height: 450px;
}
.del-btn {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 4px;
}
</style>
